<template>
  <div class="login-wrapper">
    <div class="login-card">
      <!-- 左侧图片 -->
      <div class="login-left">
        <img src="~@/assets/login/left.png" alt="login image">
      </div>

      <!-- 右侧表单 -->
      <div class="login-right">
        <h2 class="login-title">山东万华软件科技信息公司</h2>

        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="top" class="login-form"
          autoComplete="on">
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入登录账号"
              prefix-icon="iconfont icon-yonghu_zhanghao_wode" />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password" class="password-item">
            <el-input v-model="loginForm.password" :type="pwdType" placeholder="请输入密码"
              prefix-icon="iconfont icon-mima" />
            <span class="toggle-pwd" @click="showPwd">
              <i :class="pwdType === 'password' ? 'iconfont icon-xianshi_chakan' : 'iconfont icon-yincang'"></i>
            </span>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code" class="code-item">
            <el-input v-model="loginForm.verifycode" placeholder="请输入验证码" />
            <!-- 点击刷新验证码 -->
            <img :src="apicaptchaImg" alt="验证码" class="imgCode" @click="loadCaptcha" />

          </el-form-item>



          <!-- 默认账号提示 -->
          <div class="default-tips">
            默认登录名：admin | 默认密码：wanhua开头
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button type="primary" :loading="loading" class="login-btn" @click.native.prevent="handleLogin">
              登 录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // 水波纹指令
import axios from 'axios'
import {
  mapGetters,
  mapActions
} from 'vuex'
export default {
  name: 'login',
  directives: {
    waves
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    return {
      tenant: this.tenantid || 'OpenAuthDBContext', //当前选择的租户
      tenants: [{
        value: 'OpenAuthDBContext',
        label: '系统程序'
      }],
      loginForm: {
        username: '',
        password: '',
        ranval: '',
        verifycode: ''

      },
      apicaptchaImg: '', // 接口返回的验证码图片
      loginRules: {
        username: [{
          required: true,
          trigger: 'blur',
          validator: validateUsername
        }],
        password: [{
          required: true,
          trigger: 'blur',
          validator: validatePass
        }]
      },
      loading: false,
      pwdType: 'password',
      identifyCode: ''
    }
  },
  computed: {
    ...mapGetters([
      'isIdentityAuth',
      'tenantid',
    ])
  },
  created() {

    this.loadCaptcha(); // 页面创建时加载验证码
  },
  methods: {
    ...mapActions([
      'setTenantId', //
    ]),


    tenantChange(e) {
      this.setTenantId(e)
    },
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    async loadCaptcha() {
      this.loginForm.ranval = this.getRandom32();
      try {
        const res = await axios.get(process.env.VUE_APP_BASE_API + '/Check/verify?ranval=' + this.loginForm.ranval); // 调用接口
        this.apicaptchaImg = res.data.result;       // 页面显示
        console.log('验证码加载成功', res);
      } catch (err) {
        console.error('验证码加载失败', err);
      }
    },
    getRandom32() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 32; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    handleLogin() {

      let that = this;
      that.loading = true;


      this.$refs.loginForm.validate(valid => {
        if (valid) {
          that.loading = true;

          that.$store.dispatch('Login', this.loginForm).then(() => {
            this.loading = false;
            this.$router.push({ path: '/' });
          }).catch(() => {
            that.loadCaptcha();
            that.loginForm.verifycode = '';
            this.loading = false;
          })


        } else {
          return false
        }
      })

      setTimeout(() => {
        this.loading = false;
      }, 3000);
    },
    // 修改验证码
    changeCode(val) {
      this.identifyCode = val
    }
  }
}
</script>


<style lang="scss" scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5f6fa;
  padding: 20px;

  .login-card {
    display: flex;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    max-width: 900px;
    width: 100%;
    transition: all 0.3s ease;

    @media screen and (max-width: 768px) {
      flex-direction: column;
      max-width: 400px;
    }

    .login-left {
      flex: 1;
      background: #4452D5;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 80%;
        max-width: 400px;
      }

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .login-right {
      flex: 1;
      padding: 40px 30px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .login-title {
        font-size: 24px;
        font-weight: 600;
        color: #4452D5;
        margin-bottom: 20px;
      }

      .login-form {
        .el-form-item {
          margin-bottom: 25px;

          input {
            border-radius: 6px;
            box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
          }
        }

        .password-item {
          position: relative;

          .toggle-pwd {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            font-size: 20px;
            color: #888;
          }
        }

        .code-item {
          display: flex;
          align-items: center;

          .el-input {
            flex: 1;
          }

          .imgCode {
            margin-left: 10px;
            cursor: pointer;
          }
        }

        .default-tips {
          font-size: 12px;
          color: #888;
          margin-bottom: 15px;
        }

        .login-btn {
          width: 100%;
          height: 50px;
          font-size: 18px;
          background: #4452D5;
          border-radius: 6px;
        }
      }
    }
  }
}
</style>